package cn.xuchunh.guava.collection;

import com.google.common.collect.*;

import java.util.Iterator;
import java.util.List;

/**
 * Created on 2017/4/4.
 * <p>
 * <p><a href="http://wiki.jikexueyuan.com/project/google-guava-official-tutorial/expand-tools.html">集合扩展工具类</a></p>
 *
 * @author XCH
 */
public class ExUtilities {

    public static void main(String[] args) {
//        peekingIterator();
//        abstractIterator();
        abstractSequentialIterator();
    }

    private void forwarding() {
        AddLoggingList<String> loggingList = new AddLoggingList<>(Lists.newArrayList());
        // do something
    }

    private static void peekingIterator() {

        // Iterators.peekingIterator 返回的 PeekingIterator 不支持在 peek()操作之后调用remove()方法。

        List<String> list = Lists.newArrayList("a", "a", "b", "b", "c", "c");
        PeekingIterator<String> peekingIterator = Iterators.peekingIterator(list.iterator());
        List<String> result = Lists.newArrayList();
        while (peekingIterator.hasNext()) {
            String current = peekingIterator.next();
            while (peekingIterator.hasNext() && peekingIterator.peek().equals(current)) {
                peekingIterator.next();
            }
            result.add(current);
        }
        System.out.println(result);
    }

    private static void abstractIterator() {
        // AbstractIterator 继承了 UnmodifiableIterator，所以禁止实现 remove()方法。
        // 如果你需要支持 remove()的迭代器，就不应该继承 AbstractIterator。
        List<String> list = Lists.newArrayList("a", null, null, "a", "b", null);
        System.out.println(Iterators.toString(skipNulls(list.iterator())));
    }

    private static Iterator<String> skipNulls(final Iterator<String> in) {
        return new AbstractIterator<String>() {
            @Override
            protected String computeNext() {
                while (in.hasNext()) {
                    String s = in.next();
                    if (s != null) {
                        return s;
                    }
                }
                return endOfData();
            }
        };
    }

    private static void abstractSequentialIterator(){
        // 你必须额外传入一个初始值，或者传入 null 让迭代立即结束。
        // 因为 computeNext(T)假定 null 值意味着迭代的末尾——AbstractSequentialIterator 不能用来实现可能返回 null 的迭代器。
        Iterator<Integer> iterator = new AbstractSequentialIterator<Integer>(1) {
            @Override
            protected Integer computeNext(Integer previous) {
                return (previous == 1 << 30) ? null : previous * 2;
            }
        };
        System.out.println(Iterators.toString(iterator));
    }

}
